package com.hk.app.utils;

import com.hk.Mgr.web.dto.ProductStaticInfoCacheDTO;
import com.hk.commons.*;
import com.hk.commons.RedisCilent;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.ProductInfo;
import org.json.JSONObject;

/**
 *
 * @author Antinomy
 * @date 17/2/21
 */
public class RedisUtils {

    /**
     * expire info 30 mins
     */
    public static final int PRD_EXPIRE = 60*30;

    public static OrderInfo getOrderInfo(Long orderId) {
        return getOrderInfo(ConstantsOrder.ORDER_FYJZH_PRIX + orderId);
    }

    public static OrderInfo getOrderInfo(String keyStr) {

        OrderInfo orderInfo = null;

        // 从缓存中获取预授权订单
        if (RedisCilent.existsKey(keyStr)) {
            String orderStr = RedisCilent.getString(keyStr);
            orderInfo = JsonUtils.toBean(orderStr, OrderInfo.class);
        }

        return orderInfo;
    }

    public static ProductStaticInfoCacheDTO getProductCache(Long productId) {

        String productCacheKey =  ConstantProduct.PRODUCT_STATIC_INFO_CACHE_PRE +productId;

        ProductStaticInfoCacheDTO result = null;
        // 从缓存中获取产品缓存信息
        if (RedisCilent.existsKey(productCacheKey)) {
            String cacheStr = RedisCilent.getString(productCacheKey);
            result = JsonUtils.toBean(cacheStr, ProductStaticInfoCacheDTO.class);
        }

        return result;
    }

    public static ProductStaticInfoCacheDTO setProductCache(ProductInfo prodInfo) {
        ProductStaticInfoCacheDTO result = new ProductStaticInfoCacheDTO();
        CglibBeanUtils.copy(result,prodInfo);

        RedisCilent.setString(
                ConstantProduct.PRODUCT_STATIC_INFO_CACHE_PRE + prodInfo.getId(),
                new JSONObject(result).toString(),
                PRD_EXPIRE);

        return result;
    }
}
